<template>
  <div style="margin-bottom: 20px">
    <span style="font-size: 18px;font-weight: bold">
      {{ desc }}
      数据量：{{ totalSamples }}
    </span>
    <br>
  </div>
  <el-row>
    <el-col :span="12">
      <el-alert
          :title="searchAlertText"
          type="warning"
          style="margin-bottom: 10px;"
          v-show="showSearchAlert"
          @close="onSearchAlertClose"
          closable
      />
      <div style="text-align: left">
        <el-input style="width: 120px" class="item" :placeholder="'1 ≤ id ≤ ' + totalSamples"
                  v-model="searchingIndex" :disabled="changeSampleLoading">
        </el-input>
        <el-button @click="onSearchButtonClick" class="item" round v-loading="changeSampleLoading">
          <i class="el-icon-search"></i>
          查找指定样例
        </el-button>
      </div>
    </el-col>
    <el-col :span="12">
      <div style="text-align: right">
        <el-button-group v-loading="changeSampleLoading">
          <el-button type="primary" round @click="onPreviousSampleClick">上一样例</el-button>
          <el-button type="primary" round @click="onRandomSampleClick">随机样例</el-button>
          <el-button type="primary" round @click="onNextSampleClick">下一样例</el-button>
        </el-button-group>
      </div>
    </el-col>
  </el-row>
  <el-divider/>
  <el-card class="box-card" v-loading="changeSampleLoading">
    <template #header>
      <div class="card-header">
        <h3 style="display: inline">样例{{ currentSampleIndex + 1 }}：</h3>
      </div>
    </template>
    <div class="text item" v-html="currentSampleText"/>
    <el-divider/>
    <el-row>
      <el-col :span="22">
        <span style="font-weight: bold">选项（点击后显示答案）：</span>
        <el-button v-for="(each, index) in currentSampleCandidates"
                   :key="'choice-making-' + name + '-button-' + index"
                   :type="chooseButtonType[index]"
                   :icon="chooseButtonIcon[index]"
                   @click="onChooseButtonClick(each, index)"
                   style="margin-bottom: 10px"
        >
          {{ each }}
        </el-button>
      </el-col>
      <el-col :span="2" style="text-align: right">
        <el-button type="primary" round @click="onFillClick">提交</el-button>
      </el-col>
    </el-row>
  </el-card>
  <div v-for="each in resultCardList" :key="'choice-making-' + name + '-task-card-' + each.cardIndex">
    <el-divider/>
    <choice-making-task-card
        :sample-id="each.index" :text="each.text"
        :candidates="each.candidates"
        :answer="each.answer"
        :name="name"
        :namespace="namespace"
        @close="onCardClose(each.cardIndex)"/>
  </div>
</template>

<script>
import ChoiceMakingTaskCard from "./ChoiceMakingTaskCard.vue";
import {defineComponent, ref} from 'vue'
import {ElMessage} from "element-plus";

export default defineComponent({
  name: "ChoiceMakingTask",
  components: {
    ChoiceMakingTaskCard
  },
  data() {
    return {
      resultCardList: [],
      resultCardIndex: 0,
      totalSamples: 0,
      currentSampleIndex: 0, // 0 <= currentSampleIndex < totalSamples
      currentSampleText: '',
      currentSampleCandidates: [],
      chooseButtonIcon: [],
      chooseButtonType: [],
      showSearchAlert: false,
      searchAlertText: '',
      searchingIndex: ref(''),
      changeSampleLoading: true,
      choiceIndex: '',
      answer: ''
    }
  },
  props: {
    name: String,
    desc: String,
    namespace: String,
  },
  mounted() {
    this.axios.get('/' + this.namespace + '/sample').then(response => {
      this.totalSamples = response.data.samples
      this.changeSampleLoading = false
      this.onChangeSample(0)
    }).catch(err => {
      ElMessage('获取选择填空：' + this.name + '样例数失败, 详情见控制台')
      console.log(err)
    })
  },
  methods: {
    onCardClose(cardIndex) {
      for (let i = 0; i < this.resultCardList.length; ++i) {
        if (this.resultCardList[i].cardIndex === cardIndex) {
          this.resultCardList.splice(i, 1);
          break;
        }
      }
    },
    onChangeSample(index) {
      this.changeSampleLoading = true
      this.axios.get('/' + this.namespace + '/sample', {
        params: {
          index: index
        }
      }).then(response => {
        switch (this.name) {
          case 'C3': {
            this.currentSampleText = '阅读文本：\n' + response.data.text + '\n回答问题：' +
                response.data.question.replace('[MASK]',
                '<span style="color: red; ">[请填入适当的选项]</span>')
            this.currentSampleCandidates = response.data.candidates
            this.answer = response.data.answer
            this.chooseButtonIcon = []
            this.chooseButtonType = []
            for (let i = 0; i < this.currentSampleCandidates.length; ++i) {
              this.chooseButtonIcon.push('el-icon-warning-outline')
              this.chooseButtonType.push('primary')
            }
            break
          }
          case 'CHID': {
            this.currentSampleText = response.data.text.replace('[MASK]',
                '<span style="color: red; ">[请填入适当的选项]</span>')
            this.currentSampleCandidates = response.data.candidates
            this.answer = response.data.answer
            this.chooseButtonIcon = []
            this.chooseButtonType = []
            for (let i = 0; i < this.currentSampleCandidates.length; ++i) {
              this.chooseButtonIcon.push('el-icon-warning-outline')
              this.chooseButtonType.push('primary')
            }
            break
          }
          case 'AFQMC': {
            this.currentSampleText = '句子1: ' + response.data.sentence1 +
                '；    句子2: ' + response.data.sentence2
            this.currentSampleCandidates = response.data.candidates
            this.answer = response.data.answer
            this.chooseButtonIcon = []
            this.chooseButtonType = []
            for (let i = 0; i < this.currentSampleCandidates.length; ++i) {
              this.chooseButtonIcon.push('el-icon-warning-outline')
              this.chooseButtonType.push('primary')
            }
            break
          }
          default: {
            throw 'unknown name: ' + this.name
          }
        }
        this.changeSampleLoading = false
      }).catch(err => {
        ElMessage('获取' + '样例' + index + '失败, 详情见控制台')
        console.log(err)
        this.changeSampleLoading = false
      })
    },
    onNextSampleClick() {
      this.currentSampleIndex += 1
      this.checkCurrentSampleIndex()
      this.onChangeSample(this.currentSampleIndex)
    },
    onPreviousSampleClick() {
      this.currentSampleIndex -= 1
      this.checkCurrentSampleIndex()
      this.onChangeSample(this.currentSampleIndex)
    },
    onRandomSampleClick() {
      this.currentSampleIndex = Math.floor(Math.random() * this.totalSamples)
      this.checkCurrentSampleIndex()
      this.onChangeSample(this.currentSampleIndex)
    },
    checkCurrentSampleIndex() {
      if (this.currentSampleIndex < 0) {
        this.currentSampleIndex = this.totalSamples - 1
      } else if (this.currentSampleIndex >= this.totalSamples) {
        this.currentSampleIndex = 0
      }
    },
    onSearchButtonClick() {
      let index = Number(this.searchingIndex)
      if (!Number.isInteger(index) || index < 1 || index > this.totalSamples) {
        this.showSearchAlert = true
        this.searchAlertText = '请输入1到' + this.totalSamples + '的整数'
        return
      }
      this.currentSampleIndex = index - 1
      this.checkCurrentSampleIndex()
      this.onChangeSample(this.currentSampleIndex)
    },
    onFillClick() {
      let copyList = []
      for (let each of this.currentSampleCandidates) {
        copyList.push(each)
      }
      this.resultCardList.unshift({
        index: this.currentSampleIndex,
        text: this.currentSampleText,
        candidates: copyList,
        answer: this.answer,
        cardIndex: this.resultCardIndex
      })
      this.resultCardIndex += 1
    },
    onChooseButtonClick(choice, index) {
      for (let i = 0; i < this.currentSampleCandidates.length; ++i) {
        if (this.currentSampleCandidates[i] === this.answer) {
          this.chooseButtonIcon[i] = 'el-icon-check'
          this.chooseButtonType[i] = 'success'
        } else {
          this.chooseButtonIcon[i] = 'el-icon-close'
          this.chooseButtonType[i] = 'info'
        }
      }
      if (choice !== this.answer) {
        this.chooseButtonIcon[index] = 'el-icon-close'
        this.chooseButtonType[index] = 'danger'
      }
    },
    onSearchAlertClose() {
      this.showSearchAlert = false
    },
  }
})
</script>

<style scoped>
.box-card {
  width: 100%;
  text-align: left;
  margin-top: 10px;
}

.item {
  margin: 5px;
}
</style>